<template>
  <div>
    <el-row :gutter="20">
      <div class="app-container">
        <el-row type="flex" justify="start" align="middle">
          <el-col :span="2"
            ><span class="el-custom-title">产线</span></el-col
          >
          <el-col :span="15" style="font-size:13px;">
            <span>编号: </span>
            <el-autocomplete
              class="inline-input"
              style="max-width:120px;font-size:13px;"
              v-model="selectedNo"
              :fetch-suggestions="querySearch"
              placeholder="请输入编号"
              @select="handleSelect"
              @input="handleInput"
            ></el-autocomplete>
            <span>更新时间: </span>
            <el-date-picker
              style="max-width:280px;font-size:13px;"
              v-model="selectedDatetimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDateSelectChange"
            >
            </el-date-picker>
            <span>状态: </span>
            <el-select
              v-model="queryConditions.status"
              placeholder="请选择"
              style="max-width:120px;font-size:13px;"
            >
              <el-option
                v-for="itm in this.lstStatus"
                :label="itm.label"
                :value="itm.value"
                :key="itm.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="7" style="float:right;">
            <el-button-group>
              <el-button
                type="primary"
                icon="el-icon-search"
                class="el-button--mini"
                @click="ui_query"
                >查询</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-plus"
                class="el-button--mini"
                @click="handleCreate"
                >添加</el-button
              >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="handleUpdate()"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="ui_delete(null, null)"
              >
                删除
              </el-button>
            </el-button-group>
            <el-button-group>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-s-check"
                @click="ui_auditing()"
              >
                提交审核
              </el-button>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-s-check"
                ref="btnAudited"
                @click="ui_audited(null, null)"
                >审核</el-button
              >
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-document-copy"
                @click="ui_dispatch()"
              >
                下发
              </el-button>
            </el-button-group>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start">
          <el-table
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            @row-click="rowClick"
            @selection-change="handleSelectionChange"
            ref="dispatchTable"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column align="center" label="id" width="95" v-if="false">
              <template slot-scope="scope">
                {{ scope.row.id }}
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              label="订单id"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.orderId }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="订单编号"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.orderNo }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="产品ID"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.productId }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="产品编号"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.productNo }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="产线编号"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.produceLineNo }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="产线名称"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.produceLineName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工序线编号"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.sourceLineNo }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工序线名称"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.sourceLineName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="所属工厂"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.factoryId }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="所属工厂"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.factoryName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="状态"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.status | resolveStatusValue(lstStatus) }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="来源"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{
                  scope.row.sourceLineType
                    | resolveSourceLineTypeValue(lstSourceLineType)
                }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="备注"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.comment }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="审核时间"
              width="100"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.audittime | formatDate }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="审核人"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.audituser }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="创建时间"
              width="100"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.createtime | formatDate }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="创建人"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.createuser }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="更新时间"
              width="100"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.updatetime | formatDate }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="更新人"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.updateuser }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="删除时间"
              width="100"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.deletetime | formatDate }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="删除人"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.deleteuser }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="版本"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.version }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="是否已删除"
              width="95"
              style="display:none;"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.isdeleted }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="MOD时间"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.modTime }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="观测时间" width="95">
              <template slot-scope="scope">
                {{ scope.row.watchTime }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="计算时间方法"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.calcuteTimeMethod }}
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            :page-sizes="listQuery.pageSizes"
            @pagination="fetchData"
          />
        </el-row>
      </div>
    </el-row>
    <el-row>
      <el-tabs type="border-card">
        <el-tab-pane label="工序支线">
          <mesprocedurebranchchild
            :mesproduceProcedureid="
              this.lstSelected != null && this.lstSelected.length > 0
                ? this.lstSelected[0].id
                : 0
            "
          ></mesprocedurebranchchild>
        </el-tab-pane>
        <el-tab-pane label="工序">
          <mesprocedurechild
            :mesproduceProcedureid="
              this.lstSelected != null && this.lstSelected.length > 0
                ? this.lstSelected[0].id
                : 0
            "
          ></mesprocedurechild>
        </el-tab-pane>
        <el-tab-pane label="工艺"> </el-tab-pane>
        <el-tab-pane label="工序动作组">配置管理</el-tab-pane>
        <el-tab-pane label="工序动作库">角色管理</el-tab-pane>
        <el-tab-pane label="工序变量">定时任务补偿</el-tab-pane>
        <el-tab-pane label="工序要求">定时任务补偿</el-tab-pane>
        <el-tab-pane label="观测工时">定时任务补偿</el-tab-pane>
      </el-tabs>
    </el-row>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      ref="dialog"
    >
      <div
        class="app-container"
        v-if="dialogStep == 1"
        style="text-align:center"
      >
        <el-row>
          <el-button @click="importFromProduct(0)">
            从产品工序线导入
          </el-button> </el-row
        ><el-row>
          <el-button @click="importFromProduct(1)">
            从生产工序线导入
          </el-button>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer" v-if="dialogStep == 1">
        <el-button @click="dialogImportVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
          v-if="false"
        >
          确定
        </el-button>
      </div>

      <div class="app-container" v-if="dialogStep == 2">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="left"
          label-width="120px"
          style="width: 400px; margin-left: 50px"
        >
          <el-form-item label="选择订单" prop="orderId">
            <el-select
              v-model="temp.orderId"
              class="filter-item"
              placeholder="请选择订单"
              @change="handleOrderSelectChange"
            >
              <el-option
                v-for="item in this.ddOrders"
                :key="item.id"
                :label="item.orderNo"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品" prop="productId">
            <el-select
              v-model="temp.productId"
              class="filter-item"
              placeholder="请选择产品"
              @change="handleProductSelectChange"
            >
              <el-option
                v-for="item in this.ddProducts"
                :key="item.productId"
                :label="item.productNo"
                :value="item.productId"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="生产工序线编号"
            prop="produceProcedureNo"
            v-if="this.importSource == 2"
          >
            <el-select
              v-model="temp.produceProcedureLineId"
              class="filter-item"
              placeholder="请选择工序线编号"
              @change="handleProduceLineSelectChange"
            >
              <el-option
                v-for="item in this.ddProduceLines"
                :key="item.produceProcedureId"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="生产工序线名称"
            prop="produceProcedureName"
            v-if="this.importSource == 2"
          >
            <el-input v-model="temp.produceLineBranchName" />
          </el-form-item>

          <el-form-item
            label="产品工序线编号"
            prop="produceProcedureNo"
            v-if="this.importSource == 1"
          >
            <el-select
              v-model="temp.sourceLineId"
              class="filter-item"
              placeholder="请选择工序线编号"
              @change="handleProductLineSelectChange"
            >
              <el-option
                v-for="item in this.ddProductLines"
                :key="item.productProcedureId"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="产品工序线名称"
            prop="produceProcedureName"
            v-if="this.importSource == 1"
          >
            <el-input v-model="temp.sourceLineName" />
          </el-form-item>

          <el-form-item label="产线编号" prop="produceLineNo">
            <el-input v-model="temp.produceLineNo" />
          </el-form-item>
          <el-form-item label="产线名称" prop="produceLineName">
            <el-input v-model="temp.produceLineName" />
          </el-form-item>
          <el-form-item label="所属工厂" prop="factoryId">
            <el-select
              v-model="temp.factoryId"
              class="filter-item"
              placeholder="请选择工厂"
              @change="handleFactorySelectChange"
            >
              <el-option
                v-for="item in this.ddFactories"
                :key="item.factoryId"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" v-if="dialogStep == 2">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="textMap.dispatchTxt"
      :visible.sync="dialogDispatchVisible"
    >
      <el-form
        ref="dispatchForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="选择工厂" prop="facctoryId">
          <el-select
            v-model="selectedFactoryId"
            class="filter-item"
            placeholder="请选择工厂"
            @change="handleFactorySelectChange"
          >
            <el-option
              v-for="item in this.ddFactories"
              :key="item.factoryId"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDispatchVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="dispatch_create">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAll,
  getOne,
  getList,
  create,
  update,
  deleteBatch,
  saveRelation
} from "@/api/produceLine/modelProduceLine";

import { getAll as getAllProduceProcedures } from "@/api/procedure/produce/mesProduceProcedure";
import { getAll as getAllProductProcedureLines } from "@/api/procedure/product/mesProductProcedure";
import { getAll as getAllOrderProductNoDtls } from "@/api/sale/saleOrderProductNoDtl";
import { getAll as getAllFactories } from "@/api/produceLine/ModelProcessFactory";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import mesprocedurebranchchild from "@/views/procedure/produce/mesproduceBranchChild";
import store from "@/store/index";
import moment from "moment";
import { formatDate } from "@/utils/date";
import mesprocedurechild from "@/views/procedure/produce/mesProcedureChild";
import {
  create as dispatchCreate,
  update as updateDispatch,
  getList as getDispatchList
} from "@/api/procedure/product/modelProductProcedureDispatch";

export default {
  components: { Pagination, mesprocedurebranchchild, mesprocedurechild },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentproduceProcedureId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      dialogImportStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
        import: "导入"
      },

      //表格變量
      lstSelected: [],
      ddProduceLines: [],
      ddFactories: [],
      rules: {
        orderId: [
          {
            type: "number",
            min: 1,
            required: true,
            message: "订单编号不能为空！",
            trigger: "change"
          }
        ],
        productId: [
          {
            type: "number",
            min: 1,
            required: true,
            message: "产品编号不能为空！",
            trigger: "change"
          }
        ],
        produceLineBBranchNo: [
          {
            validator: this.excludeDeaultStringValidate,
            trigger: "change"
          }
        ],
        produceLineBBranchName: [
          {
            required: true,
            message: "生成工序线名称不能为空！",
            trigger: "change"
          }
        ],
        watchTime: [
          {
            required: true,
            message: "观测时间为空！",
            trigger: "change"
          }
        ],
        modTime: [
          {
            required: true,
            message: "MOD时间不能为空！",
            trigger: "change"
          }
        ],
        calcuteTimeMethod: [
          {
            required: true,
            message: "计算时间方法不能为空！",
            trigger: "change"
          }
        ],
        produceLineNo: [
          {
            required: true,
            message: "产线编号不能为空！",
            trigger: "change"
          }
        ],
        produceLineName: [
          {
            required: true,
            message: "产线名称不能为空！",
            trigger: "change"
          }
        ],
        factoryId: [
          {
            type: "number",
            min: 1,
            required: true,
            message: "所属工厂不能为空！",
            trigger: "change"
          }
        ]
      },
      temp: {
        id: 0,
        produceLineNo: "",
        produceLineName: "",
        orderId: 0,
        orderNo: "",
        productId: 0,
        productNo: "",
        factoryId: 0,
        factoryName: "",
        produceLineBranchId: 0,
        produceLineBranchNo: "",
        produceLineBranchName: "",
        ordered: "",
        comment: "",
        audittime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        audituser: "",
        createtime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        createuser: "",
        updatetime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        updateuser: "",
        deletetime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        deleteuser: "",
        isdeleted: 0,
        status: 0,
        modTime: "",
        watchTime: "",
        calcuteTimeMethod: "",
        version: "",
        relationId: 0, //中间表Id
        sourceLineId: 0, //源工序线Id
        sourceLineNo: "", //源工序线编号
        sourceLineName: "", //源工序线名称
        sourceLineType: 0 //1:产品工序 2: 生产工序
      },
      queryConditions: {
        no: "",
        updateStartTime: moment(new Date(1900, 5, 27, 15, 44, 11)).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        updateEndTime: "", //moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        status: -1
      },
      lstStatus: [
        { label: "请选择", value: -1 },
        { label: "已提交", value: 0 },
        { label: "未审核", value: 1 },
        { label: "已审核", value: 2 },
        { label: "审核未通过", value: 3 }
      ],
      lstSourceLineType: [
        { label: "未知", value: 0 },
        { label: "产品工序线", value: 1 },
        { label: "生产工序线", value: 2 }
      ],

      selectedNo: "",
      ddOrders: [], //订单
      cacheddProduts: [], //订单缓存
      ddProducts: [], //产品
      dialogStep: 1,
      selectedDatetimeRange: [],
      importSource: 1, //1:表示从产品工序线导入;2：表示从生产工序线导入
      ddProductLines: [], //生产工序线集合
      dialogDispatchVisible: false,
      selectedFactoryId: 0 //所选工厂
    };
  },
  filters: {
    resolveEnableValue(p) {
      return p ? "是" : "否";
    },
    formatDate(nowTime) {
      var moment = require("moment");
      return moment(nowTime).format("YYYY-MM-DD HH:mm:ss");
    },
    resolveStatusValue(p, options) {
      if (p == null || options == null) return "未知";
      let itm = options.find(v => {
        return v.value == p;
      });
      return itm == null ? "未知" : itm.label;
    },
    resolveSourceLineTypeValue(p, options) {
      if (p == null || options == null) return "未知";
      let itm = options.find(v => {
        return v.value == p;
      });
      return itm == null ? "未知" : itm.label;
    }
  },
  computed: {
    audittime: {
      get() {
        return moment(this.temp.audittime).format("YYYY-MM-DD HH:mm:ss");
      },
      set(val) {
        this.temp.audittime = moment(val).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    createtime: {
      get() {
        return moment(this.temp.createtime).format("YYYY-MM-DD HH:mm:ss");
      },
      set(val) {
        this.temp.createtime = moment(val).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    updatetime: {
      get() {
        return moment(this.temp.updatetime).format("YYYY-MM-DD HH:mm:ss");
      },
      set(val) {
        this.temp.updatetime = moment(val).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    deletetime: {
      get() {
        return moment(this.temp.deletetime).format("YYYY-MM-DD HH:mm:ss");
      },
      set(val) {
        this.temp.deletetime = moment(val).format("YYYY-MM-DD HH:mm:ss");
      }
    }
  },
  watch: {},
  created() {
    this.fetchData();
    this.getAllOrderProductNos();
    this.getAllFactories();
    this.getAllproduceProcedures();
    this.getAllProductProcedureLines();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
    },
    fetchData() {
      this.listLoading = true;
      let params = {
        page: this.listQuery.page,
        size: this.listQuery.limit
      };
      params = Object.assign(params, this.queryConditions);
      getList(params).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    ui_query() {
      this.$loading = true;
      getList(this.queryConditions).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.$loading = false;
      });
    },
    ui_create() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = 0; //自增
          this.temp.sourceLineType = this.importSource;
          saveRelation(this.temp).then(response => {
            this.temp.id = response.data.id;
            this.fetchData();
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_update() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          //解构?
          let { productNo, orderNo, ...rest } = this.temp;
          saveRelation(this.temp).then(response => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      if (this.lstSelected == null || this.lstSelected.length === 0) {
        this.$message.error("请先选择要删除的工序组");
        return;
      }
      let ids = [];
      this.lstSelected.map(function(elm) {
        ids.push(elm.id);
      });
      deleteBatch(ids).then(() => {
        ids.forEach(elm => {
          const index = this.list.findIndex(v => v.id === elm);
          this.list.splice(index, 1);
        });
        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: 0,
        produceLineNo: "",
        produceLineName: "",
        orderId: 0,
        orderNo: "",
        productId: 0,
        productNo: "",
        factoryId: 0,
        factoryName: "",
        produceLineBranchId: 0,
        produceLineBranchNo: "",
        produceLineBranchName: "",
        ordered: "",
        comment: "",
        audittime: "", //moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        audituser: "",
        createtime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        createuser: "",
        updatetime: "", //moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        updateuser: "",
        deletetime: "", //moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        deleteuser: "",
        isdeleted: 0,
        status: 0,
        modTime: "",
        watchTime: "",
        calcuteTimeMethod: "",
        version: "",
        relationId: 0,
        sourceLineId: 0, //源工序线Id
        sourceLineNo: "", //源工序线编号
        sourceLineName: "", //源工序线名称
        sourceLineType: 0 //1:产品工序 2: 生产工序
      };
    },
    handleCreate() {
      this.dialogStep = 1;
      this.dialogFormVisible = true;
    },
    handleUpdate() {
      if (this.lstSelected == null || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条产品工序线");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.dialogStep = 2;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    rowClick(row, column, event) {
      this.lstSelected.length = 0;
      this.lstSelected.push(row);
      this.currentproduceProcedureId = row.id;
    },
    handleMainTypeChange(val) {
      this.getSelParentIdOptions();
    },
    querySearch(queryString, cb) {
      let produceLines = this.ddProduceLines;
      let results = queryString
        ? produceLines.filter(this.createFilter(queryString))
        : produceLines;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return p => {
        return p.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    getAllproduceProcedures() {
      this.ddProduceLines.length = 0;
      getAllProduceProcedures().then(response => {
        let r = response.data.map(v => {
          return {
            value: v.id,
            label: v.produceProcedureNo,
            produceLineNo: v.produceProcedureNo,
            produceLineName: v.produceProcedureName
          };
        });
        this.ddProduceLines = this.ddProduceLines.concat(r);
      });
    },
    getAllFactories() {
      this.$loading = true;
      this.ddFactories.length = 0;
      this.ddFactories.splice(0, 0, {
        value: 0,
        label: "请选择",
        sFactoryNo: "请选择",
        sFactoryName: "请选择",
        factoryId: 0
      });
      getAllFactories().then(response => {
        this.$loading = false;
        let r = response.data.map(v => {
          return {
            value: v.id,
            label: v.sfactoryname,
            sFactoryNo: v.sfactoryno,
            sFactoryName: v.sfactoryname,
            factoryId: v.id
          };
        });
        this.ddFactories = this.ddFactories.concat(r);
      });
    },
    handleSelect(val) {
      this.queryConditions.no = val.value;
    },
    handleInput(val) {
      this.queryConditions.no = val;
    },
    handleDateSelectChange(val) {
      // console.log(val);
      this.queryConditions.updateStartTime = moment(val[0]).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      this.queryConditions.updateEndTime = moment(val[1]).format(
        "YYYY-MM-DD HH:mm:ss"
      );
    },
    ui_auditing() {
      if (this.lstSelected == null || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条产品工序线");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]);
      //提交审核
      this.temp.status = 1;
      //解构
      let { productNo, orderNo, ...rest } = this.temp;
      update(rest).then(response => {
        this.fetchData();
        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "提交审核成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    ui_audited() {
      if (this.lstSelected == null || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条产品工序线");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]);
      let text = this.$refs.btnAudited.$el.innerText;
      if (text == "审核") {
        //审核通过
        this.temp.status = 2;
      } else {
        //撤销审核
        this.temp.status = 3;
      }
      let { productNo, orderNo, ...rest } = this.temp;
      update(rest).then(response => {
        this.fetchData();
        this.dialogFormVisible = false;

        if (text == "审核") {
          //审核通过
          this.$refs.btnAudited.$el.innerText = "撤销审核";
        } else {
          //审核撤销
          this.$refs.btnAudited.$el.innerText = "审核";
        }
        this.$notify({
          title: "Success",
          message: text + "成功！",
          type: "success",
          duration: 2000
        });
      });
    },

    //生产工序线选择事件
    handleProduceLineBranchSelectChange(val) {
      if (val != null) {
        let itm = this.ddProduceLineBranchs.find(v => {
          return v.value == val;
        });
        if (itm != null) {
          this.temp.produceLineBranchName = itm.produceLineBranchName;
          this.temp.produceLineBranchId = itm.produceLineBranchId;
          this.temp.produceLineBranchNo = itm.produceLineBranchNo;
        } else {
          this.temp.produceLineBranchName = "";
          this.temp.produceLineBranchId = 0;
          this.temp.produceLineBranchNo = "";
        }
      }
    },
    getAllOrderProductNos() {
      this.ddOrders.length = 0;
      this.ddProducts.length = 0;
      this.cacheddProduts.length = 0;
      sessionStorage.setItem("products", null);
      this.ddOrders.push({ id: 0, orderNo: "请选择" });
      this.ddProducts.splice(0, 0, {
        productId: 0,
        productNo: "请选择"
      });
      getAllOrderProductNoDtls().then(response => {
        let r = response.data.map(v => {
          //订单遍号
          let index = this.ddOrders.findIndex(o => {
            return o.id == v.sdorderId;
          });
          if (index < 0) {
            this.ddOrders.push({ id: v.sdorderId, orderNo: v.orderNo });
          }

          //产品编号
          let index2 = this.ddProducts.findIndex(o => {
            return o.productId == v.productId;
          });
          if (index2 < 0) {
            this.ddProducts.push({
              productId: v.productId,
              productNo: v.productNo
            });
          }
        });
        this.cacheddProducts = response.data;
        sessionStorage.setItem(
          "products",
          JSON.stringify(this.cacheddProducts)
        );
      });
    },
    handleOrderSelectChange(val) {
      this.cacheddProducts = JSON.parse(sessionStorage.getItem("products"));
      if (val == 0) {
      } else {
        //赋值订单号
        let itm = this.ddOrders.find(v => {
          return v.id == val;
        });

        this.temp.orderId = val;
        this.temp.orderNo = itm.orderNo;
        this.ddProducts.length = 0;
        this.cacheddProducts.map(o => {
          if (o.sdorderId == val) {
            this.ddProducts.push({
              productId: o.productId,
              productNo: o.productNo
            });
          }
        });
        this.ddProducts.splice(0, 0, {
          productId: 0,
          productNo: "请选择",
          sdOrderId: 0,
          orderNo: "请选择"
        });
      }
    },
    //规则验证器
    excludeDeaultStringValidate(rule, value, callback) {
      if (value == 0 || String(value).indexOf("请选择") >= 0) {
        callback("必须选择一项");
      } else {
        callback();
      }
    },
    importFromProduct(p) {
      //从产品工序线包含从生产工序线生成的逻辑，暂时只实现第一种

      if (p == 0 || p == 1) {
        this.resetTemp();
        this.dialogStatus = "create";
        this.dialogStep = 2;

        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });

        if (p == 0) {
          this.importSource = 1;
        } else {
          this.importSource = 2;
        }
      }
    },
    handleFactorySelectChange(val) {
      if (val != null) {
        let itm = this.ddFactories.find(v => {
          return v.factoryId == val;
        });
        if (itm != null) {
          this.temp.factoryId = itm.factoryId;
          this.temp.factoryName = itm.sFactoryName;
        }
      }
    },
    handleProductSelectChange(val) {
      if (val != null) {
        let itm = this.ddProducts.find(v => {
          return val == v.productId;
        });
        if (itm != null) {
          this.temp.productId = itm.productId;
          this.temp.productNo = itm.productNo;
        }
      }
    },
    //查询所有的产品工序线
    getAllProductProcedureLines() {
      this.ddProductLines.length = 0;
      getAllProductProcedureLines().then(response => {
        let r = response.data.map(v => {
          return {
            value: v.id,
            label: v.productProcedureNo,
            productLineNo: v.productProcedureNo,
            productLineName: v.productProcedureName
          };
        });
        this.ddProductLines = this.ddProductLines.concat(r);
      });
    },
    //生产工序线选择事件
    handleProductLineSelectChange(val) {
      if (val != null) {
        let itm = this.ddProductLines.find(v => {
          return v.value == val;
        });
        if (itm != null) {
          this.temp.sourceLineId = itm.value;
          this.temp.sourceLineNo = itm.productLineNo;
          this.temp.sourceLineName = itm.productLineName;
        } else {
          this.temp.sourceLineId = 0;
          this.temp.sourceLineNo = "";
          this.temp.sourceLineName = "";
        }
      }
    },
    //查询所有的产品工序线
    getAllProduceProcedureLines() {
      this.ddProduceLines.length = 0;
      getAllProduceProcedureLines().then(response => {
        let r = response.data.map(v => {
          return {
            value: v.id,
            label: v.ProduceProcedureNo,
            ProduceLineNo: v.ProduceProcedureNo,
            ProduceLineName: v.ProduceProcedureName
          };
        });
        this.ddProduceLines = this.ddProduceLines.concat(r);
      });
    },
    //生产工序线选择事件
    handleProduceLineSelectChange(val) {
      if (val != null) {
        let itm = this.ddProduceLines.find(v => {
          return v.value == val;
        });
        if (itm != null) {
          this.temp.sourceLineId = itm.value;
          this.temp.sourceLineNo = itm.ProduceLineNo;
          this.temp.sourceLineName = itm.ProduceLineName;
        } else {
          this.temp.sourceLineId = 0;
          this.temp.sourceLineNo = "";
          this.temp.sourceLineName = "";
        }
      }
    },
    //下发
    ui_dispatch() {
      if (this.lstSelected == null || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条产品工序线");
        return;
      }
      //判断此产线是否已被下发过
      getDispatchList({
        produceLineId: this.lstSelected[0].id,
        isDeleted: 0
      }).then(response => {
         let lstExits = response.data.records;
        if (lstExits != null && lstExits.length > 0) {
          this.$notify({
            title: "提示",
            message: "此产线已经下发",
            type: "error",
            duration: 2000
          });
          this.lstSelected.length = 0;
          this.$refs["dispatchTable"].clearSelection();
        } else {
          this.temp = Object.assign({}, this.lstSelected[0]);
          this.dialogDispatchVisible = true;
        }
      });
    },
    dispatch_create() {
      var param = {
        id: 0,
        productProcedureLineId: this.temp.sourceLineId, //产品工序线Id
        factoryId: this.selectedFactoryId,
        produceLineId: this.temp.id, //产线Id
        createUser: store.getters.name,
        createtime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        comment: "",
        status: 0, //已提交
        isDeleted: false,
        verson: 1,
        sourceLineType: this.temp.sourceLineType //产线来源
      };
      dispatchCreate(param).then(response => {
        this.dialogDispatchVisible = false;
        this.$notify({
          title: "Success",
          message: "下发成功！",
          type: "success",
          duration: 2000
        });
      });
    }
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
